package net.kleinhenz.norabase.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import net.kleinhenz.norabase.server.model.RuneEntry;
import net.kleinhenz.norabase.shared.model.Rune;

public class CollectionHTMLImporter {

	public static List<RuneEntry> parsePoxNoraHTML(String data) throws IOException{

		List<RuneEntry> result = new ArrayList<RuneEntry>();
		
		// step 1 : read file into buffer
		List<String> buf = new ArrayList<String>();
	    String line = null;
        BufferedReader br = new BufferedReader(new StringReader(data));
	    while ((line=br.readLine())!=null)	{
	    	buf.add(line);
	    }
    	br.close();

	    // step 2 : find <tr> containers
		List<String> trList = new ArrayList<String>();
    	boolean inTR = false;
    	StringBuffer cLine = new StringBuffer();
    	for (int i=0; i<buf.size(); i++) {
    		String l = buf.get(i);
	    	if (l.contains("<tr>") && buf.size()>i && buf.get(i+1).contains("runeStoreItemCount")) {
	    		inTR = true;
	    		cLine.append(l);
	    	} else 	if (inTR && !l.contains("</tr>"))
	    		cLine.append(l);
	    	else if (inTR && l.contains("</tr>")) {
	    		cLine.append(l);
	    		inTR = false;
	    		trList.add(cleanup(cLine));
	    		cLine = new StringBuffer();
	    	}
	    }
    	
    	// step 3 : extract data
    	buf.clear();
    	for (String l : trList) {
    		String r = l.replaceAll(".*runeStoreItemCount\">([0-9]*)&nbsp;&nbsp;</td><td><a href=\"#\" onclick=\"return loadRunePreview\\('(.)', ([0-9]*),.*", "$1;$2;$3");
    		if (!r.startsWith(";"))
    			buf.add(r);    		    		
    	}
    	
    	// step 4 :  construct result
    	for (String l : buf) {
    		StringTokenizer t = new StringTokenizer(l, ";");
    		if (t.countTokens()!=3)
    			throw new IOException("Error importing collection - wrong token count: " + l);
    		Integer count = new Integer(t.nextToken());
    		String type = t.nextToken();
    		if ("C".equals(type))
    			type = Rune.CHAMPION;
    		else if ("E".equals(type))
    			type = Rune.EQUIPMENT;
    		else if ("R".equals(type))
    			type = Rune.RELIC;
    		else if ("S".equals(type))
    			type = Rune.SPELL;
    		Integer id = new Integer(t.nextToken());
    		RuneEntry entry = new RuneEntry(id, type);
    		entry.setCount(count);
    		result.add(entry);
    	}    	
    	
    	return result;
	}
	
	private static String cleanup(StringBuffer cLine) {

		StringBuffer target = new StringBuffer();
		for (int i=0;i<cLine.length();i++) {
			char c = cLine.charAt(i);
			if (c!='\n' && c!='\r' && c!='\t')
				target.append(c);
		}
		return target.toString();
	}
}
